package com.cuckoo.cuckoo_app2.thread;

import android.util.Log;

import com.cuckoo.cuckoo_app2.apiAsync.BaseCallbac;
import com.cuckoo.cuckoo_app2.dao.SiteLink;
import com.cuckoo.cuckoo_app2.model.JavaScriptParameterModel;
import com.cuckoo.cuckoo_app2.model.JavaScriptResponseModel;
import com.cuckoo.cuckoo_app2.utils.JavaScroptConsoleUtils;
import com.cuckoo.cuckoo_app2.utils.JavaScroptParameterUtils;
import com.cuckoo.cuckoo_app2.utils.MD5Utils;
import com.cuckoo.cuckoo_app2.utils.NetworkRequestHelperUtils;
import com.google.gson.Gson;
import com.quickjs.JSContext;
import com.quickjs.JSObject;
import com.quickjs.QuickJS;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class LoginTaskTherad implements Runnable {

    private SiteLink siteLink;
    private String userName;
    private String password;
    private BaseCallbac<JavaScriptResponseModel> callbac;
    private String codeValue;
    private String codeKey;

    public LoginTaskTherad(SiteLink siteLink, String userName, String password, String codeKey, String codeValue, BaseCallbac<JavaScriptResponseModel> callbac) {
        this.password = password;
        this.userName = userName;
        this.callbac = callbac;
        this.siteLink = siteLink;
        this.codeValue = codeValue;
        this.codeKey = codeKey;
    }

    @Override
    public void run() {
        if (userName == null || password == null) {
            callbac.onFailure("用户名或密码不能为空");
            return;
        }

        siteLink.setLoginUrl("http://192.168.31.18:7076/common/login");

        // 开始请求网路
        Map<String, String> bodyMap = new HashMap<>();
        bodyMap.put("url", siteLink.getLoginUrl());
        bodyMap.put("name", userName);
        bodyMap.put("pass", password);
        bodyMap.put("codeKey", codeKey);
        bodyMap.put("codeValue", codeValue);

        Gson gson = new Gson();
        QuickJS quickJS = QuickJS.createRuntimeWithEventQueue();
        JSContext contextParam = quickJS.createContext();
        JSContext contextRespon = quickJS.createContext();

        try {
            contextParam.addJavascriptInterface(new MD5Utils(), "md5Utils");
            contextParam.addJavascriptInterface(new JavaScroptConsoleUtils(), "console");
            contextParam.addJavascriptInterface(new JavaScroptParameterUtils(bodyMap), "parameter");

            //        siteLink.setLoginCodeBefore("""
            //                    function getParameterHandler() {
            //                        let url = parameter.getMap("url")
            //                        let obj = {
            //                            username: parameter.getMap("name"),
            //                            password: parameter.getMap("pass"),
            //                            cToken: parameter.getMap("codeKey"),
            //                            captcha: parameter.getMap("codeValue")
            //                        }
            //                        console.log(JSON.stringify(obj))
            //                        let headers = {}
            //                        return {
            //                            mediaType: "form",
            //                            requestType: "POST",
            //                            url: url,
            //                            headers: JSON.stringify(headers),
            //                            body: JSON.stringify(obj)
            //                        }
            //                    }
            //                    getParameterHandler()
            //                    """
            //        );

            JSObject parameterObj = contextParam.executeObjectScript(siteLink.getLoginCodeBefore(), "script.js");
            JavaScriptParameterModel parameterModel = new JavaScriptParameterModel();
            parameterModel.setUrl(parameterObj.getString("url"));
            parameterModel.setMediaType(parameterObj.getString("mediaType"));
            parameterModel.setRequestType(parameterObj.getString("requestType"));
            parameterModel.setBody(parameterObj.getString("body"));
            parameterModel.setHeaders(parameterObj.getString("headers"));
            HashMap<String, String> headersMap = gson.fromJson(parameterModel.getHeaders(), HashMap.class);

            String response = "";
            if (parameterModel.getRequestType().equals("POST") && parameterModel.getMediaType().equals("json")) {
                response = NetworkRequestHelperUtils.postJson(
                        parameterModel.getUrl(),
                        parameterModel.getBody(),
                        headersMap
                );
            } else if (parameterModel.getRequestType().equals("POST") && parameterModel.getMediaType().equals("form")) {
                response = NetworkRequestHelperUtils.postForm(
                        parameterModel.getUrl(),
                        parameterModel.getBody(),
                        headersMap
                );
            } else if (parameterModel.getRequestType().equals("GET")) {
                response = NetworkRequestHelperUtils.get(parameterModel.getUrl(), headersMap);
            }

            Map<String, String> responseMap = new HashMap<>();
            responseMap.put("res", response);

            // 处理返回后的数据
            //        siteLink.setLoginCodeAfter("""
            //                    function getResponseHandler() {
            //                            let res = response.getMap("res")
            //                            res = JSON.parse(res)
            //                            let code = "500"
            //                            let message = res["message"]
            //                            let dataKey = ""
            //                            let dataValue = ""
            //                            if (res["code"] == 200) {
            //                                let data = res["data"]
            //                                code = "200"
            //                                dataKey ="Authorization"
            //                                dataValue = data["tokenHead"] +" "+ data["token"]
            //                            } else if (res["code"] == "401") {
            //                                code = "300"
            //                            } else {
            //                                code = "500"
            //                            }
            //                            return {
            //                                code: code,
            //                                message: message,
            //                                dataKey: dataKey,
            //                                dataValue: dataValue
            //                            }
            //                    }
            //                    getResponseHandler()
            //                    """
            //        );

            contextRespon.addJavascriptInterface(new JavaScroptParameterUtils(responseMap), "response");
            JSObject responseObj = contextRespon.executeObjectScript(siteLink.getLoginCodeAfter(), "script.js");
            JavaScriptResponseModel responseModel = new JavaScriptResponseModel();
            responseModel.setCode(responseObj.getString("code"));
            responseModel.setMessage(responseObj.getString("message"));
            responseModel.setDataKey(responseObj.getString("dataKey"));
            responseModel.setDataValue(responseObj.getString("dataValue"));

            Log.i("TEST", responseModel.getMessage());
            if (responseModel.getCode().equals("200")) {
                callbac.onSuccess(responseModel);
            } else {
                callbac.onFailure(responseModel.getMessage());
            }
        } catch (IOException e) {
            callbac.onFailure("服务器请求失败");
            quickJS.close();
        } catch (Exception e) {
            callbac.onFailure("应用执行错误");
            quickJS.close();
        }finally {
            // 关闭js
            contextParam.close();
            contextParam = null;

            // 关闭js
            contextRespon.close();
            contextRespon = null;

            // 关闭JS
            quickJS.close();
            quickJS = null;
        }

    }

}
